<template>
  <div class="drag-drop-manager">
    <!-- 拖拽预览 -->
    <div 
      v-if="dragState.isDragging && dragState.dragComponent"
      class="drag-preview"
      :style="dragPreviewStyle"
    >
      <div class="drag-preview-header">
        <div class="preview-icon">
          <i :class="getWidgetIcon(dragState.dragComponent.type)"></i>
        </div>
        <div class="preview-info">
          <div class="component-name">{{ dragState.dragComponent.name || dragState.dragComponent.type }}</div>
          <div class="component-type">{{ getComponentTypeName(dragState.dragComponent.type) }}</div>
        </div>
        <div class="preview-status">
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      
      <div class="drag-preview-content">
        <div class="preview-description">
          {{ getComponentDescription(dragState.dragComponent) }}
        </div>
        <div class="preview-actions">
          <span class="action-tip">拖拽到目标区域</span>
        </div>
      </div>
    </div>
    
    <!-- 拖拽指示器 -->
    <div 
      v-if="dragState.isDragging && dragState.dropTarget"
      class="drag-indicator"
      :style="dragIndicatorStyle"
    >
      <div class="indicator-content">
        <div class="indicator-icon">
          <i class="el-icon-plus"></i>
        </div>
        <div class="indicator-text">
          <span>放置到 {{ dragState.dropTarget.name || dragState.dropTarget.type }}</span>
        </div>
      </div>
    </div>
    
    <!-- 性能监控面板 -->
    <div 
      v-if="dragState.isDragging && performanceMetrics.fps > 0"
      class="performance-panel"
    >
      <div class="performance-header">
        <i class="el-icon-monitor"></i>
        <span>性能监控</span>
      </div>
      <div class="performance-content">
        <div class="perf-item">
          <span class="perf-label">FPS:</span>
          <span class="perf-value" :class="getFPSClass(performanceMetrics.fps)">
            {{ performanceMetrics.fps }}
          </span>
        </div>
        <div class="perf-item">
          <span class="perf-label">内存:</span>
          <span class="perf-value">{{ performanceMetrics.memoryUsage }}MB</span>
        </div>
        <div class="perf-item">
          <span class="perf-label">操作:</span>
          <span class="perf-value">{{ performanceMetrics.dragOperations }}</span>
        </div>
      </div>
    </div>
    
    <!-- 历史记录面板 -->
    <div 
      v-if="dragHistory.operations.length > 0"
      class="history-panel"
    >
      <div class="history-header">
        <i class="el-icon-time"></i>
        <span>操作历史</span>
        <div class="history-actions">
          <button 
            @click="undoOperation"
            :disabled="dragHistory.currentIndex < 0"
            class="history-btn undo-btn"
            title="撤销 (Ctrl+Z)"
          >
            <i class="el-icon-refresh-left"></i>
          </button>
          <button 
            @click="redoOperation"
            :disabled="dragHistory.currentIndex >= dragHistory.operations.length - 1"
            class="history-btn redo-btn"
            title="重做 (Ctrl+Y)"
          >
            <i class="el-icon-refresh-right"></i>
          </button>
        </div>
      </div>
      <div class="history-content">
        <div class="history-list">
          <div 
            v-for="(operation, index) in dragHistory.operations"
            :key="operation.id"
            class="history-item"
            :class="{
              'current': index === dragHistory.currentIndex,
              'can-undo': index <= dragHistory.currentIndex,
              'can-redo': index > dragHistory.currentIndex
            }"
          >
            <div class="history-item-header">
              <span class="history-type">{{ getOperationTypeLabel(operation.type) }}</span>
              <span class="history-time">{{ formatTime(operation.timestamp) }}</span>
            </div>
            <div class="history-description">{{ operation.description }}</div>
            <div class="history-meta">
              <span class="meta-item">距离: {{ operation.metadata.dragDistance }}px</span>
              <span class="meta-item">时长: {{ operation.metadata.dragDuration }}ms</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 统计面板 -->
    <div 
      v-if="dragStatistics.totalOperations > 0"
      class="statistics-panel"
    >
      <div class="statistics-header">
        <i class="el-icon-data-analysis"></i>
        <span>拖拽统计</span>
        <div class="statistics-actions">
          <button 
            @click="toggleStatisticsPanel"
            class="stats-btn toggle-btn"
            title="切换面板 (Ctrl+S)"
          >
            <i class="el-icon-arrow-down"></i>
          </button>
          <div class="export-dropdown">
            <button 
              @click="toggleExportMenu"
              class="stats-btn export-btn"
              title="导出统计 (Ctrl+E)"
            >
              <i class="el-icon-download"></i>
            </button>
            <div class="export-menu" v-show="exportMenuVisible">
              <button @click="() => { exportStatistics(); closeExportMenu(); }" class="export-option">
                <i class="el-icon-document"></i>
                <span>JSON格式</span>
              </button>
              <button @click="() => { exportStatisticsCSV(); closeExportMenu(); }" class="export-option">
                <i class="el-icon-document-copy"></i>
                <span>CSV格式</span>
              </button>
              <button @click="() => { exportStatisticsHTML(); closeExportMenu(); }" class="export-option">
                <i class="el-icon-document"></i>
                <span>HTML报告</span>
              </button>
            </div>
          </div>
          <button 
            @click="confirmResetStatistics"
            class="stats-btn reset-btn"
            title="重置统计"
          >
            <i class="el-icon-refresh"></i>
          </button>
        </div>
      </div>
      <div class="statistics-content" v-show="statisticsPanelExpanded">
        <!-- 基础统计 -->
        <div class="stats-section">
          <h4 class="stats-section-title">基础统计</h4>
          <div class="stats-grid">
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-s-operation"></i>
                <span>总操作数</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.totalOperations }}</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-success"></i>
                <span>成功率</span>
              </div>
              <div class="stats-card-value">{{ Math.round(dragStatistics.successRate * 100) / 100 }}%</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-time"></i>
                <span>平均时长</span>
              </div>
              <div class="stats-card-value">{{ Math.round(dragStatistics.averageDragTime) }}ms</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-location"></i>
                <span>平均距离</span>
              </div>
              <div class="stats-card-value">{{ Math.round(dragStatistics.averageDragDistance) }}px</div>
            </div>
          </div>
        </div>
        
        <!-- 性能统计 -->
        <div class="stats-section">
          <h4 class="stats-section-title">性能统计</h4>
          <div class="stats-grid">
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-trophy"></i>
                <span>最快拖拽</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.fastestDrag === Infinity ? 0 : dragStatistics.fastestDrag }}ms</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-warning"></i>
                <span>最慢拖拽</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.slowestDrag }}ms</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-arrow-up"></i>
                <span>最快速度</span>
              </div>
              <div class="stats-card-value">{{ Math.round(dragStatistics.fastestSpeed) }}px/s</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-arrow-down"></i>
                <span>最慢速度</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.slowestSpeed === Infinity ? 0 : Math.round(dragStatistics.slowestSpeed) }}px/s</div>
            </div>
          </div>
        </div>
        
        <!-- 操作类型分布 -->
        <div class="stats-section">
          <h4 class="stats-section-title">操作类型分布</h4>
          <div class="stats-chart">
            <div 
              v-for="(count, type) in dragStatistics.operationTypeCounts"
              :key="type"
              class="chart-bar"
              :style="{ height: getBarHeight(count) }"
              :title="`${getOperationTypeLabel(type)}: ${count}`"
            >
              <span class="chart-label">{{ getOperationTypeLabel(type) }}</span>
              <span class="chart-value">{{ count }}</span>
            </div>
          </div>
        </div>
        
        <!-- 时间分布 -->
        <div class="stats-section">
          <h4 class="stats-section-title">24小时操作分布</h4>
          <div class="stats-chart hourly-chart">
            <div 
              v-for="(count, hour) in dragStatistics.hourlyDistribution"
              :key="hour"
              class="chart-bar hourly-bar"
              :style="{ height: getHourlyBarHeight(count) }"
              :title="`${hour}:00 - ${count}次操作`"
            >
              <span class="chart-label">{{ hour }}:00</span>
              <span class="chart-value">{{ count }}</span>
            </div>
          </div>
        </div>
        
        <!-- 用户行为统计 -->
        <div class="stats-section">
          <h4 class="stats-section-title">用户行为统计</h4>
          <div class="stats-grid">
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-refresh-left"></i>
                <span>撤销次数</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.userBehavior.undoCount }}</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-refresh-right"></i>
                <span>重做次数</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.userBehavior.redoCount }}</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-delete"></i>
                <span>清空历史</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.userBehavior.clearHistoryCount }}</div>
            </div>
            <div class="stats-card">
              <div class="stats-card-header">
                <i class="el-icon-download"></i>
                <span>导出次数</span>
              </div>
              <div class="stats-card-value">{{ dragStatistics.userBehavior.exportCount }}</div>
            </div>
          </div>
        </div>
        
        <!-- 性能分析报告 -->
        <div class="stats-section">
          <h4 class="stats-section-title">性能分析报告</h4>
          <div class="performance-report">
            <div class="performance-summary">
              <div class="perf-indicator">
                <span class="perf-label">性能等级:</span>
                <span class="perf-grade" :class="getPerformanceGrade()">
                  {{ getPerformanceGradeText() }}
                </span>
              </div>
              <div class="perf-indicator">
                <span class="perf-label">优化建议:</span>
                <span class="perf-suggestions">{{ getPerformanceSuggestions().length }}条</span>
              </div>
            </div>
            
            <div class="performance-trends">
              <h5>性能趋势 (最近10次操作)</h5>
              <div class="trend-chart">
                <div 
                  v-for="(fps, index) in dragStatistics.performanceTrends.fps.slice(-10)"
                  :key="index"
                  class="trend-bar"
                  :style="{ height: getTrendBarHeight(fps) }"
                  :class="getTrendBarClass(fps)"
                  :title="`操作${index + 1}: ${fps} FPS`"
                >
                  <span class="trend-value">{{ fps }}</span>
                </div>
              </div>
            </div>
            
            <div class="performance-recommendations">
              <h5>优化建议</h5>
              <div class="recommendation-list">
                <div 
                  v-for="(rec, index) in getPerformanceSuggestions()"
                  :key="index"
                  class="recommendation-item"
                  :class="rec.type"
                >
                  <div class="rec-header">
                    <i :class="getRecommendationIcon(rec.type)"></i>
                    <span class="rec-title">{{ rec.title }}</span>
                  </div>
                  <div class="rec-description">{{ rec.description }}</div>
                  <div class="rec-action">{{ rec.action }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, inject, onMounted, onUnmounted, ref } from 'vue'
import { 
  DragOperationType, 
  generateOperationId, 
  generateOperationDescription,
  getWidgetIcon,
  getComponentTypeName,
  getComponentDescription,
  isDescendant,
  getComponentLevel,
  findComponentById,
  canAcceptDrop,
  calculateDropScore,
  findBestDropTarget,
  generateComponentHtml,
  getOperationTypeLabel,
  formatTime,
  throttle,
  clearThrottleTimers,
  calculateDistance,
  calculateSpeed,
  getFPSClass,
  getPerformanceGrade,
  getPerformanceGradeText,
  getPerformanceSuggestions,
  getRecommendationIcon,
  getTrendBarHeight,
  getTrendBarClass,
  getBarHeight,
  getHourlyBarHeight
} from '@/utils/dragDrop'
import { useHistoryManager } from '@/utils/historyManager'
import { useStatisticsManager } from '@/utils/statisticsManager'

// 注入的依赖
const injectedDragState = inject('dragState', null)
const designerStore = inject('designerStore')

// 使用内部拖拽状态，但如果有外部注入的状态则同步
const internalDragState = ref({
  isDragging: false,
  dragType: null,
  dragComponent: null,
  dragSource: null,
  dropTarget: null,
  dragPosition: { x: 0, y: 0 },
  dragOffset: { x: 0, y: 0 },
  dragStartTime: 0,
  dragStartPosition: { x: 0, y: 0 }
})

// 如果有外部注入的状态，使用外部状态，否则使用内部状态
const dragState = injectedDragState || internalDragState

// 状态同步函数
const syncDragState = (updates) => {
  if (injectedDragState) {
    // 同步到外部状态
    Object.assign(injectedDragState.value, updates)
  }
  Object.assign(internalDragState.value, updates)
}

// 拖拽状态管理
const dragMetrics = ref({
  distance: 0,
  duration: 0,
  speed: 0,
  isValidDrop: false
})

// 使用历史管理器
const { 
  history: dragHistory, 
  canUndo, 
  canRedo, 
  recordOperation, 
  undoOperation: historyUndo, 
  redoOperation: historyRedo, 
  clearHistory: historyClear,
  exportHistory: historyExport,
  importHistory: historyImport
} = useHistoryManager()

// 使用导入的拖拽操作类型枚举

// 使用统计管理器
const { 
  statistics: dragStatistics, 
  performanceMetrics, 
  updateDragStatistics, 
  updatePerformanceMetrics, 
  updateUserBehaviorStats,
  resetStatistics,
  exportStatistics,
  exportStatisticsCSV,
  exportStatisticsHTML,
  generateStatisticsReport,
  getStatisticsSummary,
  getStatisticsSummarySimple,
  saveStatisticsToStorage,
  loadStatisticsFromStorage
} = useStatisticsManager()

// 拖拽节流和性能优化配置
const throttleConfig = {
  move: 16, // 60fps
  update: 32, // 30fps
  render: 100 // 10fps
}

// 本地节流定时器管理
const throttleTimers = ref({
  move: null,
  update: null,
  render: null
})

// 性能监控系统 - 使用统计管理器中的performanceMetrics

let frameCount = 0
let lastTime = performance.now()
let memoryCheckInterval = null

// 拖拽音效系统
const audioContext = ref(null)
const audioEnabled = ref(true)

const initAudioContext = () => {
  try {
    audioContext.value = new (window.AudioContext || window.webkitAudioContext)()
  } catch (error) {
    console.warn('音频上下文初始化失败:', error)
    audioEnabled.value = false
  }
}

// 更新拖拽预览样式
const updateDragPreviewStyle = () => {
  // 根据拖拽指标动态调整预览样式
  const previewElement = document.querySelector('.drag-preview')
  if (!previewElement) return
  
  // 根据拖拽速度调整动画
  if (dragMetrics.value.speed > 500) {
    previewElement.style.filter = 'blur(1px)'
  } else {
    previewElement.style.filter = 'blur(0px)'
  }
  
  // 根据拖拽距离调整透明度
  const opacity = Math.max(0.7, 1 - dragMetrics.value.distance / 1000)
  previewElement.style.opacity = opacity
  
  // 根据拖拽时长调整缩放
  const scale = 1 + Math.min(0.1, dragMetrics.value.duration / 10000)
  previewElement.style.transform = `scale(${scale})`
}

// 拖拽统计信息显示
const showDragStats = () => {
  if (dragMetrics.value.duration < 500) return // 只显示有意义的拖拽
  
  const stats = {
    distance: Math.round(dragMetrics.value.distance),
    duration: Math.round(dragMetrics.value.duration),
    speed: Math.round(dragMetrics.value.speed),
    success: !!dragState.value.dropTarget
  }
  
  // 创建统计信息提示
  const statsElement = document.createElement('div')
  statsElement.className = 'drag-stats-toast'
  statsElement.innerHTML = `
    <div class="stats-header">
      <i class="el-icon-${stats.success ? 'success' : 'warning'}"></i>
      <span>拖拽统计</span>
    </div>
    <div class="stats-content">
      <div class="stat-item">
        <span class="stat-label">距离:</span>
        <span class="stat-value">${stats.distance}px</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">时长:</span>
        <span class="stat-value">${stats.duration}ms</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">速度:</span>
        <span class="stat-value">${stats.speed}px/s</span>
      </div>
    </div>
  `
  
  document.body.appendChild(statsElement)
  
  // 3秒后自动移除
  setTimeout(() => {
    if (statsElement.parentNode) {
      statsElement.parentNode.removeChild(statsElement)
    }
  }, 3000)
}

// 使用从 @/utils/dragDrop 导入的函数
// generateOperationId 和 generateOperationDescription 已从工具文件导入

// 显示通知
const showNotification = (message, type = 'info') => {
  const notificationElement = document.createElement('div')
  notificationElement.className = `notification ${type}`
  notificationElement.innerHTML = `
    <i class="el-icon-${type}"></i>
    <span>${message}</span>
  `
  
  document.body.appendChild(notificationElement)
  
  setTimeout(() => {
    if (notificationElement.parentNode) {
      notificationElement.parentNode.removeChild(notificationElement)
    }
  }, 3000)
}

// 执行撤销操作
const executeUndo = (operation) => {
  try {
    switch (operation.type) {
      case DragOperationType.ADD:
        return undoAddOperation(operation)
      case DragOperationType.MOVE:
        return undoMoveOperation(operation)
      case DragOperationType.DELETE:
        return undoDeleteOperation(operation)
      case DragOperationType.MODIFY:
        return undoModifyOperation(operation)
      case DragOperationType.REORDER:
        return undoReorderOperation(operation)
      default:
        console.warn('未知的操作类型:', operation.type)
        return false
    }
  } catch (error) {
    console.error('执行撤销操作失败:', error)
    return false
  }
}

// 执行重做操作
const executeRedo = (operation) => {
  try {
    switch (operation.type) {
      case DragOperationType.ADD:
        return redoAddOperation(operation)
      case DragOperationType.MOVE:
        return redoMoveOperation(operation)
      case DragOperationType.DELETE:
        return redoDeleteOperation(operation)
      case DragOperationType.MODIFY:
        return redoModifyOperation(operation)
      case DragOperationType.REORDER:
        return redoReorderOperation(operation)
      default:
        console.warn('未知的操作类型:', operation.type)
        return false
    }
  } catch (error) {
    console.error('执行重做操作失败:', error)
    return false
  }
}

const playDragSound = (type) => {
  if (!audioEnabled.value || !audioContext.value) return
  
  try {
    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)
    
    // 根据类型设置不同的音效
    switch (type) {
      case 'start':
        oscillator.frequency.setValueAtTime(800, audioContext.value.currentTime)
        oscillator.frequency.exponentialRampToValueAtTime(400, audioContext.value.currentTime + 0.1)
        break
      case 'target':
        oscillator.frequency.setValueAtTime(600, audioContext.value.currentTime)
        oscillator.frequency.setValueAtTime(800, audioContext.value.currentTime + 0.05)
        oscillator.frequency.setValueAtTime(600, audioContext.value.currentTime + 0.1)
        break
      case 'success':
        oscillator.frequency.setValueAtTime(523, audioContext.value.currentTime) // C5
        oscillator.frequency.setValueAtTime(659, audioContext.value.currentTime + 0.1) // E5
        oscillator.frequency.setValueAtTime(784, audioContext.value.currentTime + 0.2) // G5
        break
      case 'fail':
        oscillator.frequency.setValueAtTime(400, audioContext.value.currentTime)
        oscillator.frequency.exponentialRampToValueAtTime(200, audioContext.value.currentTime + 0.2)
        break
      case 'undo':
        oscillator.frequency.setValueAtTime(400, audioContext.value.currentTime)
        oscillator.frequency.exponentialRampToValueAtTime(200, audioContext.value.currentTime + 0.2)
        break
      case 'redo':
        oscillator.frequency.setValueAtTime(600, audioContext.value.currentTime)
        oscillator.frequency.exponentialRampToValueAtTime(800, audioContext.value.currentTime + 0.05)
        oscillator.frequency.exponentialRampToValueAtTime(600, audioContext.value.currentTime + 0.1)
        break
    }
    
    gainNode.gain.setValueAtTime(0.1, audioContext.value.currentTime)
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.value.currentTime + 0.2)
    
    oscillator.start(audioContext.value.currentTime)
    oscillator.stop(audioContext.value.currentTime + 0.2)
  } catch (error) {
    console.warn('音效播放失败:', error)
  }
}

// 拖拽预览样式
const dragPreviewStyle = computed(() => {
  if (!dragState.value.isDragging || !dragState.value.dragComponent) {
    return { display: 'none' }
  }
  
  // 计算预览位置，避免超出屏幕边界
  const previewWidth = 200
  const previewHeight = 60
  const margin = 20
  
  let left = dragState.value.dragPosition.x + 10
  let top = dragState.value.dragPosition.y + 10
  
  // 检查右边界
  if (left + previewWidth > window.innerWidth - margin) {
    left = dragState.value.dragPosition.x - previewWidth - 10
  }
  
  // 检查下边界
  if (top + previewHeight > window.innerHeight - margin) {
    top = dragState.value.dragPosition.y - previewHeight - 10
  }
  
  // 确保不超出左边界和上边界
  left = Math.max(margin, left)
  top = Math.max(margin, top)
  
  // 根据拖拽状态添加动画效果
  const scale = dragState.value.dropTarget ? 1.05 : 1
  const shadow = dragState.value.dropTarget 
    ? '0 8px 24px rgba(64, 158, 255, 0.4)' 
    : '0 4px 12px rgba(0, 0, 0, 0.15)'
  
  return {
    position: 'fixed',
    left: `${left}px`,
    top: `${top}px`,
    width: `${previewWidth}px`,
    height: `${previewHeight}px`,
    zIndex: 9999,
    pointerEvents: 'none',
    transform: `scale(${scale})`,
    transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
    boxShadow: shadow
  }
})

// 拖拽指示器样式
const dragIndicatorStyle = computed(() => {
  if (!dragState.value.isDragging || !dragState.value.dropTarget) {
    return { display: 'none' }
  }
  
  // 获取目标组件的位置
  const targetElement = document.querySelector(`[data-component-id="${dragState.value.dropTarget.id}"]`)
  if (!targetElement) {
    return { display: 'none' }
  }
  
  const rect = targetElement.getBoundingClientRect()
  
  return {
    position: 'fixed',
    left: `${rect.left}px`,
    top: `${rect.top}px`,
    width: `${rect.width}px`,
    height: `${rect.height}px`,
    zIndex: 9998,
    pointerEvents: 'none',
    border: '2px solid #409eff',
    borderRadius: '4px',
    backgroundColor: 'rgba(64, 158, 255, 0.1)',
    boxShadow: '0 0 8px rgba(64, 158, 255, 0.3)'
  }
})

// 使用从 @/utils/dragDrop 导入的函数
// getWidgetIcon, getComponentTypeName, getComponentDescription 已从工具文件导入

// 拖拽事件处理
let dragStartTime = 0
let dragStartPosition = { x: 0, y: 0 }
let dragLastPosition = { x: 0, y: 0 }
let dragLastTime = 0

const handleDragStart = (event, component, type = 'new') => {
  try {
    dragStartTime = Date.now()
    dragStartPosition = { x: event.clientX, y: event.clientY }
    dragLastPosition = { x: event.clientX, y: event.clientY }
    dragLastTime = dragStartTime
    
    // 重置拖拽指标
    dragMetrics.value = {
      distance: 0,
      duration: 0,
      speed: 0,
      isValidDrop: false
    }
    
    dragState.value = {
      isDragging: true,
      dragType: type,
      dragComponent: component,
      dragSource: type === 'new' ? 'library' : 'canvas',
      dropTarget: null,
      dragPosition: { x: event.clientX, y: event.clientY },
      dragOffset: { x: 0, y: 0 }
    }
    
    // 设置拖拽数据
    if (event.dataTransfer) {
      event.dataTransfer.effectAllowed = 'copy'
      event.dataTransfer.setData('application/json', JSON.stringify({
        type: type,
        component: component
      }))
    }
    
    // 添加拖拽开始音效
    playDragSound('start')
    
    // 开始性能监控
    startPerformanceMonitoring()
    
    // 增加拖拽操作计数
    performanceMetrics.value.dragOperations++
    
  } catch (error) {
    handleError(error, 'drag-start')
  }
}

const handleDragMove = (event) => {
  if (!dragState.value.isDragging) return
  
  try {
    // 使用节流优化拖拽移动
    throttle(() => {
      const currentTime = Date.now()
      const currentPosition = { x: event.clientX, y: event.clientY }
      
      // 更新拖拽位置
      dragState.value.dragPosition = currentPosition
      
      // 计算拖拽偏移
      dragState.value.dragOffset = {
        x: event.clientX - dragStartPosition.x,
        y: event.clientY - dragStartPosition.y
      }
      
      // 计算拖拽指标
      const timeDelta = currentTime - dragLastTime
      if (timeDelta > 0) {
        const distanceDelta = Math.sqrt(
          Math.pow(currentPosition.x - dragLastPosition.x, 2) + 
          Math.pow(currentPosition.y - dragLastPosition.y, 2)
        )
        
        dragMetrics.value.distance += distanceDelta
        dragMetrics.value.duration = currentTime - dragStartTime
        dragMetrics.value.speed = distanceDelta / timeDelta * 1000 // 像素/秒
        
        dragLastPosition = currentPosition
        dragLastTime = currentTime
      }
    }, throttleConfig.move, 'move')
    
    // 使用节流优化目标检测
    throttle(() => {
      const targetComponent = findBestDropTarget(event.clientX, event.clientY)
      const previousTarget = dragState.value.dropTarget
      dragState.value.dropTarget = targetComponent
      
      // 检查目标变化
      if (targetComponent !== previousTarget) {
        if (targetComponent) {
          // 新的有效目标
          dragMetrics.value.isValidDrop = true
          playDragSound('target')
        } else {
          // 失去目标
          dragMetrics.value.isValidDrop = false
        }
      }
    }, throttleConfig.update, 'update')
    
    // 使用节流优化预览样式更新
    throttle(() => {
      updateDragPreviewStyle()
    }, throttleConfig.render, 'render')
    
  } catch (error) {
    handleError(error, 'drag-move')
  }
}

const handleDragEnd = (event) => {
  if (!dragState.value.isDragging) return
  
  try {
    const dragDuration = Date.now() - dragStartTime
    
    // 如果拖拽时间太短，可能是误操作
    if (dragDuration < 100) {
      resetDragState()
      return
    }
    
    // 处理拖拽结束逻辑
    if (dragState.value.dropTarget) {
      // 拖拽成功
      playDragSound('success')
      
      // 记录拖拽操作到历史
      const operation = {
        type: dragState.value.dragType === 'new' ? DragOperationType.ADD : DragOperationType.MOVE,
        component: dragState.value.dragComponent,
        target: dragState.value.dropTarget,
        position: dragState.value.dragPosition,
        data: {
          dragSource: dragState.value.dragSource,
          dragOffset: dragState.value.dragOffset
        }
      }
      
      recordDragOperation(operation)
      
      // 触发拖拽完成事件
      emit('drag-complete', {
        component: dragState.value.dragComponent,
        target: dragState.value.dropTarget,
        position: dragState.value.dragPosition,
        type: dragState.value.dragType,
        metrics: dragMetrics.value
      })
    } else {
      // 拖拽失败
      playDragSound('fail')
    }
    
    // 显示拖拽统计信息
    showDragStats()
    
    // 停止性能监控
    stopPerformanceMonitoring()
    
    // 清理节流定时器
    clearThrottleTimers(throttleTimers.value)
    
    resetDragState()
    
  } catch (error) {
    handleError(error, 'drag-end')
  }
}

// 使用从 @/utils/dragDrop 导入的函数
// findBestDropTarget 已从工具文件导入

// 使用从 @/utils/dragDrop 导入的函数
// calculateDropScore, findComponentById, canAcceptDrop, isDescendant 已从工具文件导入

// 使用从 @/utils/dragDrop 导入的函数
// getComponentLevel 已从工具文件导入

// 重置拖拽状态
const resetDragState = () => {
  dragState.value = {
    isDragging: false,
    dragType: 'new',
    dragComponent: null,
    dragSource: null,
    dropTarget: null,
    dragPosition: { x: 0, y: 0 },
    dragOffset: { x: 0, y: 0 }
  }
}

// 记录拖拽操作到历史
const recordDragOperation = (operation) => {
  if (dragHistory.value.isUndoRedo) return
  
  try {
    // 如果当前不在历史记录末尾，清除后面的记录
    if (dragHistory.value.currentIndex < dragHistory.value.operations.length - 1) {
      dragHistory.value.operations = dragHistory.value.operations.slice(0, dragHistory.value.currentIndex + 1)
    }
    
    // 添加新操作
    const operationRecord = {
      id: generateOperationId(),
      type: operation.type,
      component: operation.component,
      target: operation.target,
      position: operation.position,
      timestamp: Date.now(),
      description: generateOperationDescription(operation),
      data: operation.data || {},
      metadata: {
        dragDistance: dragMetrics.value.distance,
        dragDuration: dragMetrics.value.duration,
        dragSpeed: dragMetrics.value.speed
      }
    }
    
    dragHistory.value.operations.push(operationRecord)
    dragHistory.value.currentIndex++
    
    // 限制历史记录数量
    if (dragHistory.value.operations.length > dragHistory.value.maxHistory) {
      dragHistory.value.operations.shift()
      dragHistory.value.currentIndex--
    }
    
    // 更新性能指标
    performanceMetrics.value.dragOperations++
    
    // 更新统计数据
    updateDragStatistics(operationRecord)
    
    console.log('拖拽操作已记录:', operationRecord)
    
  } catch (error) {
    console.error('记录拖拽操作失败:', error)
  }
}

// 使用统计管理器中的updateDragStatistics函数

// 使用统计管理器中的getStatisticsSummary函数

// 使用统计管理器中的resetStatistics函数

// 撤销操作
const undoOperation = () => {
  if (dragHistory.value.currentIndex < 0) {
    showNotification('没有可撤销的操作', 'warning')
    return false
  }
  
  try {
    dragHistory.value.isUndoRedo = true
    
    const operation = dragHistory.value.operations[dragHistory.value.currentIndex]
    const success = executeUndo(operation)
    
    if (success) {
      dragHistory.value.currentIndex--
      showNotification(`已撤销: ${operation.description}`, 'success')
      
      // 播放撤销音效
      playDragSound('undo')
      
      return true
    } else {
      showNotification('撤销操作失败', 'error')
      return false
    }
    
  } catch (error) {
    console.error('撤销操作失败:', error)
    showNotification('撤销操作时发生错误', 'error')
    return false
  } finally {
    dragHistory.value.isUndoRedo = false
  }
}

// 重做操作
const redoOperation = () => {
  if (dragHistory.value.currentIndex >= dragHistory.value.operations.length - 1) {
    showNotification('没有可重做的操作', 'warning')
    return false
  }
  
  try {
    dragHistory.value.isUndoRedo = true
    
    dragHistory.value.currentIndex++
    const operation = dragHistory.value.operations[dragHistory.value.currentIndex]
    const success = executeRedo(operation)
    
    if (success) {
      showNotification(`已重做: ${operation.description}`, 'success')
      
      // 播放重做音效
      playDragSound('redo')
      
      return true
    } else {
      dragHistory.value.currentIndex-- // 回退索引
      showNotification('重做操作失败', 'error')
      return false
    }
    
  } catch (error) {
    console.error('重做操作失败:', error)
    showNotification('重做操作时发生错误', 'error')
    return false
  } finally {
    dragHistory.value.isUndoRedo = false
  }
}

// 使用从 @/utils/dragDrop 导入的函数
// getFPSClass 已从工具文件导入

// 暴露方法给父组件
defineExpose({
  handleDragStart,
  handleDragMove,
  handleDragEnd,
  undoOperation,
  redoOperation,
  clearHistory,
  exportHistory,
  importHistory,
  getHistory: () => dragHistory.value,
  getPerformanceMetrics: () => performanceMetrics.value,
  // 统计相关方法
  getStatisticsSummary,
  getStatisticsSummarySimple,
  exportStatistics,
  exportStatisticsCSV,
  exportStatisticsHTML,
  generateStatisticsReport,
  resetStatistics,
  updateUserBehaviorStats
})

// 生命周期
onMounted(() => {
  try {
    // 从本地存储加载统计数据
    loadStatisticsFromStorage()
    
    // 启动自动保存
    startStatisticsAutoSave()
    
    // 初始化音频上下文
    initAudioContext()
    
    // 添加全局拖拽事件监听
    document.addEventListener('dragover', handleDragMove)
    document.addEventListener('dragend', handleDragEnd)
    
    // 添加键盘快捷键监听
    document.addEventListener('keydown', handleKeyboardShortcuts)
    
    // 添加点击外部关闭导出菜单的监听
    document.addEventListener('click', handleClickOutside)
    
    // 启动性能监控
    startPerformanceMonitoring()
    
  } catch (error) {
    handleError(error, 'mount')
  }
})

onUnmounted(() => {
  try {
    // 保存统计数据
    if (dragStatistics.value.totalOperations > 0) {
      saveStatisticsToStorage()
    }
    
    // 停止自动保存
    stopStatisticsAutoSave()
    
    // 移除事件监听
    document.removeEventListener('dragover', handleDragMove)
    document.removeEventListener('dragend', handleDragEnd)
    document.removeEventListener('keydown', handleKeyboardShortcuts)
    document.removeEventListener('click', handleClickOutside)
    
    // 停止性能监控
    stopPerformanceMonitoring()
    
    // 清理节流定时器
    clearThrottleTimers()
    
    // 清理音频上下文
    if (audioContext.value) {
      audioContext.value.close()
    }
    
  } catch (error) {
    console.error('组件卸载时发生错误:', error)
  }
})

// 键盘快捷键处理
const handleKeyboardShortcuts = (event) => {
  // 检查是否在输入框中
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    return
  }
  
  if (event.ctrlKey || event.metaKey) {
    switch (event.key.toLowerCase()) {
      case 'z':
        event.preventDefault()
        if (event.shiftKey) {
          // Ctrl+Shift+Z 或 Cmd+Shift+Z = 重做
          redoOperation()
        } else {
          // Ctrl+Z 或 Cmd+Z = 撤销
          undoOperation()
        }
        break
      case 'y':
        event.preventDefault()
        // Ctrl+Y 或 Cmd+Y = 重做
        redoOperation()
        break
             case 'h':
         event.preventDefault()
         // Ctrl+H 或 Cmd+H = 显示/隐藏历史面板
         toggleHistoryPanel()
         break
       case 's':
         event.preventDefault()
         // Ctrl+S 或 Cmd+S = 切换统计面板
         toggleStatisticsPanel()
         break
             case 'e':
         event.preventDefault()
         // Ctrl+E 或 Cmd+E = 导出统计数据
         exportStatistics()
         break
      case 'i':
        event.preventDefault()
        // Ctrl+I 或 Cmd+I = 导入历史记录
        triggerImportHistory()
        break
    }
  }
}

// 切换历史面板显示
const toggleHistoryPanel = () => {
  const historyPanel = document.querySelector('.history-panel')
  if (historyPanel) {
    historyPanel.style.display = historyPanel.style.display === 'none' ? 'block' : 'none'
  }
}

// 触发导入历史记录
const triggerImportHistory = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (event) => {
    const file = event.target.files[0]
    if (file) {
      importHistory(file)
    }
  }
  input.click()
}

// 性能监控
const startPerformanceMonitoring = () => {
  // FPS监控
  const measureFPS = () => {
    frameCount++
    const currentTime = performance.now()
    
    if (currentTime - lastTime >= 1000) {
      performanceMetrics.value.fps = Math.round((frameCount * 1000) / (currentTime - lastTime))
      frameCount = 0
      lastTime = currentTime
    }
    
    requestAnimationFrame(measureFPS)
  }
  
  // 内存使用监控
  if (performance.memory) {
    memoryCheckInterval = setInterval(() => {
      performanceMetrics.value.memoryUsage = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024)
    }, 2000)
  }
  
  requestAnimationFrame(measureFPS)
}

// 停止性能监控
const stopPerformanceMonitoring = () => {
  if (memoryCheckInterval) {
    clearInterval(memoryCheckInterval)
    memoryCheckInterval = null
  }
}

// 错误处理和恢复机制
const errorState = ref({
  hasError: false,
  errorMessage: '',
  errorType: '',
  recoveryAttempts: 0
})

const maxRecoveryAttempts = 3

// 错误处理
const handleError = (error, context) => {
  console.error(`拖拽错误 [${context}]:`, error)
  
  errorState.value = {
    hasError: true,
    errorMessage: error.message || '未知错误',
    errorType: context,
    recoveryAttempts: errorState.value.recoveryAttempts + 1
  }
  
  // 尝试自动恢复
  if (errorState.value.recoveryAttempts <= maxRecoveryAttempts) {
    setTimeout(() => {
      attemptRecovery(context)
    }, 1000)
  } else {
    // 达到最大恢复次数，需要手动重置
    showErrorNotification()
  }
}

// 尝试恢复
const attemptRecovery = (context) => {
  try {
    switch (context) {
      case 'drag-start':
        resetDragState()
        break
      case 'drag-move':
        // 重新计算拖拽位置
        if (dragState.value.isDragging) {
          const currentPosition = dragState.value.dragPosition
          handleDragMove({ clientX: currentPosition.x, clientY: currentPosition.y })
        }
        break
      case 'drag-end':
        resetDragState()
        break
      case 'audio':
        // 重新初始化音频上下文
        initAudioContext()
        break
      default:
        resetDragState()
    }
    
    // 清除错误状态
    errorState.value.hasError = false
    errorState.value.errorMessage = ''
    errorState.value.errorType = ''
    
    console.log(`拖拽系统已从 ${context} 错误中恢复`)
  } catch (recoveryError) {
    console.error('恢复失败:', recoveryError)
    // 如果恢复失败，继续尝试
    if (errorState.value.recoveryAttempts < maxRecoveryAttempts) {
      setTimeout(() => {
        attemptRecovery(context)
      }, 2000)
    }
  }
}

// 显示错误通知
const showErrorNotification = () => {
  const errorElement = document.createElement('div')
  errorElement.className = 'drag-error-notification'
  errorElement.innerHTML = `
    <div class="error-header">
      <i class="el-icon-warning"></i>
      <span>拖拽系统错误</span>
    </div>
    <div class="error-content">
      <p>拖拽系统遇到严重错误，需要重新加载页面</p>
      <button onclick="location.reload()" class="error-reload-btn">重新加载</button>
    </div>
  `
  
  document.body.appendChild(errorElement)
  
  // 10秒后自动移除
  setTimeout(() => {
    if (errorElement.parentNode) {
      errorElement.parentNode.removeChild(errorElement)
    }
  }, 10000)
}

// 撤销添加操作
const undoAddOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从父组件中移除
  const parent = findComponentById(component.parentId)
  if (!parent) return false
  
  const index = parent.children.findIndex(child => child.id === component.id)
  if (index === -1) return false
  
  parent.children.splice(index, 1)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const parentElement = document.querySelector(`[data-component-id="${parent.id}"]`)
    if (parentElement) {
      // 重新渲染父组件的子组件
      const childrenHtml = parent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      parentElement.innerHTML = childrenHtml
    }
  }
  
  return true
}

// 重做添加操作
const redoAddOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从父组件中添加
  const parent = findComponentById(component.parentId)
  if (!parent) return false
  
  const index = parent.children.findIndex(child => child.id === component.id)
  if (index !== -1) return false // 确保没有重复添加
  
  parent.children.splice(index + 1, 0, component) // 在当前位置之后添加
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const parentElement = document.querySelector(`[data-component-id="${parent.id}"]`)
    if (parentElement) {
      // 重新渲染父组件的子组件
      const childrenHtml = parent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      parentElement.innerHTML = childrenHtml
    }
  }
  
  return true
}

// 撤销移动操作
const undoMoveOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从当前位置移除
  const currentParent = findComponentById(component.parentId)
  if (!currentParent) return false
  
  const currentIndex = currentParent.children.findIndex(child => child.id === component.id)
  if (currentIndex === -1) return false
  
  currentParent.children.splice(currentIndex, 1)
  
  // 添加到目标位置
  const targetParent = findComponentById(operation.target.id)
  if (!targetParent) return false
  
  const targetIndex = targetParent.children.findIndex(child => child.id === component.id)
  if (targetIndex === -1) return false
  
  targetParent.children.splice(targetIndex, 0, component)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const currentParentElement = document.querySelector(`[data-component-id="${currentParent.id}"]`)
    const targetParentElement = document.querySelector(`[data-component-id="${targetParent.id}"]`)
    
    if (currentParentElement && targetParentElement) {
      const currentChildrenHtml = currentParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      const targetChildrenHtml = targetParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      
      currentParentElement.innerHTML = currentChildrenHtml
      targetParentElement.innerHTML = targetChildrenHtml
    }
  }
  
  return true
}

// 重做移动操作
const redoMoveOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从当前位置移除
  const currentParent = findComponentById(component.parentId)
  if (!currentParent) return false
  
  const currentIndex = currentParent.children.findIndex(child => child.id === component.id)
  if (currentIndex === -1) return false
  
  currentParent.children.splice(currentIndex, 1)
  
  // 添加到目标位置
  const targetParent = findComponentById(operation.target.id)
  if (!targetParent) return false
  
  const targetIndex = targetParent.children.findIndex(child => child.id === component.id)
  if (targetIndex === -1) return false
  
  targetParent.children.splice(targetIndex, 0, component)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const currentParentElement = document.querySelector(`[data-component-id="${currentParent.id}"]`)
    const targetParentElement = document.querySelector(`[data-component-id="${targetParent.id}"]`)
    
    if (currentParentElement && targetParentElement) {
      const currentChildrenHtml = currentParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      const targetChildrenHtml = targetParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      
      currentParentElement.innerHTML = currentChildrenHtml
      targetParentElement.innerHTML = targetChildrenHtml
    }
  }
  
  return true
}

// 撤销删除操作
const undoDeleteOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从父组件中添加回来
  const parent = findComponentById(component.parentId)
  if (!parent) return false
  
  const index = parent.children.findIndex(child => child.id === component.id)
  if (index === -1) return false
  
  parent.children.splice(index, 0, component) // 在当前位置之前添加
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const parentElement = document.querySelector(`[data-component-id="${parent.id}"]`)
    if (parentElement) {
      const childrenHtml = parent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      parentElement.innerHTML = childrenHtml
    }
  }
  
  return true
}

// 重做删除操作
const redoDeleteOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从父组件中移除
  const parent = findComponentById(component.parentId)
  if (!parent) return false
  
  const index = parent.children.findIndex(child => child.id === component.id)
  if (index === -1) return false
  
  parent.children.splice(index, 1)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const parentElement = document.querySelector(`[data-component-id="${parent.id}"]`)
    if (parentElement) {
      const childrenHtml = parent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      parentElement.innerHTML = childrenHtml
    }
  }
  
  return true
}

// 撤销修改操作
const undoModifyOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 还原属性
  const originalComponent = findComponentById(operation.data.originalComponentId)
  if (!originalComponent) return false
  
  // 复制属性
  Object.keys(originalComponent).forEach(key => {
    if (key !== 'id' && key !== 'parentId' && key !== 'children') {
      component[key] = originalComponent[key]
    }
  })
  
  // 重新渲染组件
  const componentElement = document.querySelector(`[data-component-id="${component.id}"]`)
  if (componentElement) {
    const componentHtml = generateComponentHtml(component)
    componentElement.innerHTML = componentHtml
  }
  
  return true
}

// 重做修改操作
const redoModifyOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 应用属性
  const modifiedComponent = findComponentById(operation.data.modifiedComponentId)
  if (!modifiedComponent) return false
  
  // 复制属性
  Object.keys(modifiedComponent).forEach(key => {
    if (key !== 'id' && key !== 'parentId' && key !== 'children') {
      component[key] = modifiedComponent[key]
    }
  })
  
  // 重新渲染组件
  const componentElement = document.querySelector(`[data-component-id="${component.id}"]`)
  if (componentElement) {
    const componentHtml = generateComponentHtml(component)
    componentElement.innerHTML = componentHtml
  }
  
  return true
}

// 撤销重新排序操作
const undoReorderOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从当前位置移除
  const currentParent = findComponentById(component.parentId)
  if (!currentParent) return false
  
  const currentIndex = currentParent.children.findIndex(child => child.id === component.id)
  if (currentIndex === -1) return false
  
  currentParent.children.splice(currentIndex, 1)
  
  // 添加到目标位置
  const targetParent = findComponentById(operation.target.id)
  if (!targetParent) return false
  
  const targetIndex = targetParent.children.findIndex(child => child.id === component.id)
  if (targetIndex === -1) return false
  
  targetParent.children.splice(targetIndex, 0, component)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const currentParentElement = document.querySelector(`[data-component-id="${currentParent.id}"]`)
    const targetParentElement = document.querySelector(`[data-component-id="${targetParent.id}"]`)
    
    if (currentParentElement && targetParentElement) {
      const currentChildrenHtml = currentParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      const targetChildrenHtml = targetParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      
      currentParentElement.innerHTML = currentChildrenHtml
      targetParentElement.innerHTML = targetChildrenHtml
    }
  }
  
  return true
}

// 重做重新排序操作
const redoReorderOperation = (operation) => {
  const component = findComponentById(operation.component.id)
  if (!component) return false
  
  // 从当前位置移除
  const currentParent = findComponentById(component.parentId)
  if (!currentParent) return false
  
  const currentIndex = currentParent.children.findIndex(child => child.id === component.id)
  if (currentIndex === -1) return false
  
  currentParent.children.splice(currentIndex, 1)
  
  // 添加到目标位置
  const targetParent = findComponentById(operation.target.id)
  if (!targetParent) return false
  
  const targetIndex = targetParent.children.findIndex(child => child.id === component.id)
  if (targetIndex === -1) return false
  
  targetParent.children.splice(targetIndex, 0, component)
  
  // 重新渲染父组件
  if (designerStore && designerStore.currentPage) {
    const currentParentElement = document.querySelector(`[data-component-id="${currentParent.id}"]`)
    const targetParentElement = document.querySelector(`[data-component-id="${targetParent.id}"]`)
    
    if (currentParentElement && targetParentElement) {
      const currentChildrenHtml = currentParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      const targetChildrenHtml = targetParent.children.map(child => {
        const childComp = findComponentById(child.id)
        if (!childComp) return ''
        return `<div data-component-id="${childComp.id}" class="component-renderer">${childComp.name || childComp.type}</div>`
      }).join('')
      
      currentParentElement.innerHTML = currentChildrenHtml
      targetParentElement.innerHTML = targetChildrenHtml
    }
  }
  
  return true
}

// 使用从 @/utils/dragDrop 导入的函数
// generateComponentHtml, getOperationTypeLabel, formatTime 已从工具文件导入

// 清空历史记录
const clearHistory = () => {
  dragHistory.value.operations = []
  dragHistory.value.currentIndex = -1
  showNotification('历史记录已清空', 'info')
}

// 导出历史记录
const exportHistory = () => {
  try {
    const historyData = {
      operations: dragHistory.value.operations,
      exportTime: new Date().toISOString(),
      totalOperations: dragHistory.value.operations.length
    }
    
    const blob = new Blob([JSON.stringify(historyData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `drag-history-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    showNotification('历史记录已导出', 'success')
  } catch (error) {
    console.error('导出历史记录失败:', error)
    showNotification('导出失败', 'error')
  }
}

// 导入历史记录
const importHistory = (file) => {
  try {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const historyData = JSON.parse(e.target.result)
        if (historyData.operations && Array.isArray(historyData.operations)) {
          dragHistory.value.operations = historyData.operations
          dragHistory.value.currentIndex = historyData.operations.length - 1
          showNotification('历史记录已导入', 'success')
        } else {
          throw new Error('无效的历史记录格式')
        }
      } catch (parseError) {
        console.error('解析历史记录失败:', parseError)
        showNotification('导入失败：文件格式错误', 'error')
      }
    }
    reader.readAsText(file)
  } catch (error) {
    console.error('导入历史记录失败:', error)
    showNotification('导入失败', 'error')
  }
}

// 统计面板相关功能
const statisticsPanelExpanded = ref(true)
const exportMenuVisible = ref(false)

// 切换统计面板显示
const toggleStatisticsPanel = () => {
  statisticsPanelExpanded.value = !statisticsPanelExpanded.value
  showNotification(
    statisticsPanelExpanded.value ? '统计面板已展开' : '统计面板已收起', 
    'info'
  )
}

// 切换导出菜单显示
const toggleExportMenu = () => {
  exportMenuVisible.value = !exportMenuVisible.value
}

// 关闭导出菜单
const closeExportMenu = () => {
  exportMenuVisible.value = false
}

// 点击外部关闭导出菜单
const handleClickOutside = (event) => {
  const exportDropdown = event.target.closest('.export-dropdown')
  if (!exportDropdown && exportMenuVisible.value) {
    closeExportMenu()
  }
}

// 使用从 @/utils/dragDrop 导入的函数
// getBarHeight, getHourlyBarHeight 已从工具文件导入








    





// 重置统计数据的确认
const confirmResetStatistics = () => {
  if (confirm('确定要重置所有统计数据吗？此操作不可撤销。')) {
    resetStatistics()
    updateUserBehaviorStats('clearHistoryCount')
  }
}





// 定期保存统计数据
let statisticsSaveInterval = null

const startStatisticsAutoSave = () => {
  if (statisticsSaveInterval) return
  
  statisticsSaveInterval = setInterval(() => {
    if (dragStatistics.value.totalOperations > 0) {
      saveStatisticsToStorage()
    }
  }, 30000) // 每30秒保存一次
}

const stopStatisticsAutoSave = () => {
  if (statisticsSaveInterval) {
    clearInterval(statisticsSaveInterval)
    statisticsSaveInterval = null
  }
}



// 在组件挂载时加载统计数据
onMounted(() => {
  try {
    // 从本地存储加载统计数据
    loadStatisticsFromStorage()
    
    // 启动自动保存
    startStatisticsAutoSave()
    
    // 初始化音频上下文
    initAudioContext()
    
    // 添加全局拖拽事件监听
    document.addEventListener('dragover', handleDragMove)
    document.addEventListener('dragend', handleDragEnd)
    
    // 添加键盘快捷键监听
    document.addEventListener('keydown', handleKeyboardShortcuts)
    
    // 添加点击外部关闭导出菜单的监听
    document.addEventListener('click', handleClickOutside)
    
    // 启动性能监控
    startPerformanceMonitoring()
    
  } catch (error) {
    handleError(error, 'mount')
  }
})

// 使用从 @/utils/dragDrop 导入的函数
// getPerformanceGrade, getPerformanceGradeText, getPerformanceSuggestions, getRecommendationIcon, getTrendBarHeight, getTrendBarClass 已从工具文件导入
</script>

<style scoped>
.drag-drop-manager {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9999;
}

.drag-preview {
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.95), rgba(64, 158, 255, 0.85));
  color: white;
  padding: 12px;
  border-radius: 8px;
  font-size: 12px;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;
  animation: preview-enter 0.3s ease-out;
}

.drag-preview::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #67c23a, #409eff, #e6a23c);
  animation: preview-progress 2s linear infinite;
}

@keyframes preview-progress {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

@keyframes preview-enter {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(10px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.drag-preview.leaving {
  animation: preview-leave 0.2s ease-in forwards;
}

@keyframes preview-leave {
  from {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
  to {
    opacity: 0;
    transform: scale(0.8) translateY(-10px);
  }
}

.drag-preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.preview-icon {
  margin-right: 8px;
}

.preview-icon i {
  font-size: 18px;
}

.preview-info {
  flex-grow: 1;
}

.component-name {
  font-size: 14px;
  font-weight: bold;
  color: white;
}

.component-type {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.preview-status {
  margin-left: 10px;
}

.preview-status i {
  font-size: 14px;
  color: white;
}

.drag-preview-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.preview-description {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.2;
}

.preview-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
}

.action-tip {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.8);
}

.drag-indicator {
  position: absolute;
  pointer-events: none;
  animation: indicator-pulse 1.5s ease-in-out infinite;
  border-radius: 8px;
  overflow: hidden;
}

.drag-indicator::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, 
    rgba(64, 158, 255, 0.1) 0%, 
    rgba(64, 158, 255, 0.2) 50%, 
    rgba(64, 158, 255, 0.1) 100%);
  animation: indicator-shine 2s linear infinite;
}

@keyframes indicator-shine {
  0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
  100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}

@keyframes indicator-pulse {
  0%, 100% {
    opacity: 0.8;
    transform: scale(1);
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
  }
  50% {
    opacity: 1;
    transform: scale(1.02);
    box-shadow: 0 0 16px rgba(64, 158, 255, 0.5);
  }
}

/* 拖拽状态样式 */
.dragging {
  opacity: 0.6;
  transition: all 0.2s ease;
}

.drag-over {
  border: 2px dashed #409eff !important;
  background-color: rgba(64, 158, 255, 0.05) !important;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3) !important;
}

.container-widget.drag-over {
  border-color: #409eff !important;
  background-color: rgba(64, 158, 255, 0.1) !important;
}

/* 拖拽统计提示样式 */
.drag-stats-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  backdrop-filter: blur(8px);
  animation: stats-enter 0.3s ease-out;
  min-width: 200px;
}

@keyframes stats-enter {
  from {
    opacity: 0;
    transform: translateX(100%) scale(0.8);
  }
  to {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.stats-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #303133;
}

.stats-header i {
  font-size: 16px;
}

.stats-header .el-icon-success {
  color: #67c23a;
}

.stats-header .el-icon-warning {
  color: #e6a23c;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.stat-label {
  color: #606266;
}

.stat-value {
  color: #303133;
  font-weight: 500;
}

.indicator-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

.indicator-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: rgba(64, 158, 255, 0.9);
  border-radius: 50%;
  color: white;
}

.indicator-icon i {
  font-size: 12px;
}

.indicator-text {
  background: rgba(255, 255, 255, 0.95);
  padding: 4px 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 性能监控面板样式 */
.performance-panel {
  position: fixed;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 10001;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  min-width: 150px;
  animation: panel-enter 0.3s ease-out;
}

@keyframes panel-enter {
  from {
    opacity: 0;
    transform: translateY(-10px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.performance-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-size: 12px;
  font-weight: 600;
  color: #67c23a;
}

.performance-header i {
  font-size: 14px;
}

.performance-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.perf-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
}

.perf-label {
  color: #909399;
}

.perf-value {
  font-weight: 500;
  font-family: 'Courier New', monospace;
}

.fps-excellent {
  color: #67c23a;
}

.fps-good {
  color: #e6a23c;
}

.fps-fair {
  color: #f56c6c;
}

.fps-poor {
  color: #f56c6c;
  animation: pulse-warning 1s ease-in-out infinite;
}

@keyframes pulse-warning {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 错误通知样式 */
.drag-error-notification {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(245, 108, 108, 0.95);
  color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 24px rgba(245, 108, 108, 0.4);
  z-index: 10002;
  backdrop-filter: blur(12px);
  border: 2px solid rgba(255, 255, 255, 0.2);
  min-width: 300px;
  text-align: center;
  animation: error-enter 0.4s ease-out;
}

@keyframes error-enter {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.error-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
}

.error-header i {
  font-size: 20px;
  color: #fff;
}

.error-content p {
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.9);
}

.error-reload-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.error-reload-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 通知样式 */
.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #409eff;
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 10003;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  min-width: 250px;
  animation: slide-in 0.3s ease-out;
}

@keyframes slide-in {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.notification.info {
  background: #409eff;
}

.notification.success {
  background: #67c23a;
}

.notification.warning {
  background: #e6a23c;
}

.notification.error {
  background: #f56c6c;
}

.notification i {
  font-size: 18px;
}

.notification .el-icon-info {
  color: #fff;
}

.notification .el-icon-success {
  color: #fff;
}

.notification .el-icon-warning {
  color: #fff;
}

.notification .el-icon-error {
  color: #fff;
}

/* 历史记录面板样式 */
.history-panel {
  position: fixed;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 10004;
  backdrop-filter: blur(12px);
  min-width: 320px;
  max-width: 400px;
  max-height: 600px;
  animation: history-enter 0.4s ease-out;
}

@keyframes history-enter {
  from {
    opacity: 0;
    transform: translateX(100%) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 12px 12px 0 0;
}

.history-header > div:first-child {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.history-header i {
  font-size: 18px;
  color: #409eff;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.history-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: #409eff;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.history-btn:hover:not(:disabled) {
  background: #337ecc;
  transform: translateY(-1px);
}

.history-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  transform: none;
}

.undo-btn {
  background: #67c23a;
}

.undo-btn:hover:not(:disabled) {
  background: #529b2e;
}

.redo-btn {
  background: #e6a23c;
}

.redo-btn:hover:not(:disabled) {
  background: #cf9236;
}

.history-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 0;
}

.history-list {
  padding: 0;
}

.history-item {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.2s ease;
  cursor: pointer;
}

.history-item:hover {
  background: #f8f9fa;
}

.history-item.current {
  background: #e6f7ff;
  border-left: 3px solid #409eff;
}

.history-item.can-undo {
  opacity: 1;
}

.history-item.can-redo {
  opacity: 0.6;
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-type {
  background: #409eff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.history-time {
  font-size: 11px;
  color: #909399;
}

.history-description {
  font-size: 13px;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.4;
}

.history-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  font-size: 11px;
  color: #606266;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 滚动条样式 */
.history-content::-webkit-scrollbar {
  width: 6px;
}

.history-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 统计面板样式 */
.statistics-panel {
  position: fixed;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 10005;
  backdrop-filter: blur(12px);
  min-width: 320px;
  max-width: 400px;
  max-height: 600px;
  animation: statistics-enter 0.4s ease-out;
}

@keyframes statistics-enter {
  from {
    opacity: 0;
    transform: translateX(100%) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.statistics-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 12px 12px 0 0;
}

.statistics-header > div:first-child {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.statistics-header i {
  font-size: 18px;
  color: #409eff;
}

.statistics-actions {
  display: flex;
  gap: 8px;
}

.stats-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: #409eff;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.stats-btn:hover:not(:disabled) {
  background: #337ecc;
  transform: translateY(-1px);
}

.stats-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  transform: none;
}

.toggle-btn {
  background: #67c23a;
}

.toggle-btn:hover:not(:disabled) {
  background: #529b2e;
}

.export-btn {
  background: #e6a23c;
}

.export-btn:hover:not(:disabled) {
  background: #cf9236;
}

.reset-btn {
  background: #f56c6c;
}

.reset-btn:hover:not(:disabled) {
  background: #e65b5b;
}

.statistics-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 0;
}

.stats-section {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.stats-section:last-child {
  border-bottom: none;
}

.stats-section-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 12px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stats-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 12px;
  font-weight: 600;
  color: #303133;
}

.stats-card-value {
  font-size: 16px;
  font-weight: 500;
}

.stats-chart {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.chart-bar {
  flex: 1;
  background: #f5f5f5;
  border-radius: 4px;
  padding: 8px;
  text-align: center;
}

.chart-label {
  font-size: 12px;
  color: #606266;
}

.chart-value {
  font-size: 14px;
  font-weight: 500;
}

.hourly-chart {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.hourly-bar {
  flex: 1;
  background: #f5f5f5;
  border-radius: 4px;
  padding: 8px;
  text-align: center;
}

.hourly-label {
  font-size: 12px;
  color: #606266;
}

.hourly-value {
  font-size: 14px;
  font-weight: 500;
}

.export-dropdown {
  position: relative;
}

.export-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: none;
}

.export-option {
  display: block;
  padding: 8px 16px;
  color: #303133;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.export-option:hover {
  background-color: #f5f7fa;
}

.performance-report {
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.performance-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.perf-indicator {
  display: flex;
  flex-direction: column;
}

.perf-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
}

.perf-grade {
  font-size: 16px;
  font-weight: 600;
}

.grade-excellent {
  color: #67c23a;
}

.grade-good {
  color: #409eff;
}

.grade-fair {
  color: #e6a23c;
}

.grade-poor {
  color: #f56c6c;
}

.perf-suggestions {
  font-size: 12px;
  color: #909399;
}

.performance-trends {
  margin-bottom: 16px;
}

.trend-chart {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.trend-bar {
  flex: 1;
  background: #409eff;
  border-radius: 4px;
  overflow: hidden;
}

.trend-value {
  padding: 4px 8px;
  color: white;
  font-weight: 500;
}

.trend-low {
  background: #f56c6c;
}

.trend-medium {
  background: #e6a23c;
}

.trend-high {
  background: #67c23a;
}

.performance-recommendations {
  margin-top: 16px;
}

.recommendation-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.recommendation-item {
  flex: 1;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommendation-item.warning {
  background: #fff3cd;
  border-left: 4px solid #ffc107;
}

.recommendation-item.info {
  background: #d1ecf1;
  border-left: 4px solid #17a2b8;
}

.recommendation-item.success {
  background: #d4edda;
  border-left: 4px solid #28a745;
}

.rec-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.rec-title {
  font-size: 14px;
  font-weight: 600;
}

.rec-description {
  font-size: 12px;
  color: #606266;
}

.rec-action {
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}
</style>
